﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using QLKS.Templates;
using System.Data;
using Infragistics.Windows.DataPresenter;

namespace QLKS.Views
{
    /// <summary>
    /// Interaction logic for frmThuePhong.xaml
    /// </summary>
    public partial class frmThuePhong : FormTrans
    {

        int maPhieuThuePhong = -1;
        public bool UpdateSucces = false;
        Command cm = Command.None;
        //int succhua = -1;
        ViewModels.PhongViewModel Phong = null;

        //bool newrow = true;
        public bool IsEditMode
        {
            get { return (bool)GetValue(IsEditModeProperty); }
            set { SetValue(IsEditModeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsEditMode.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsEditModeProperty =
            DependencyProperty.Register("IsEditMode", typeof(bool), typeof(frmThuePhong), new UIPropertyMetadata(true));

        public DataTable tbKhachHang
        {
            get { return (DataTable)GetValue(tbKhachHangProperty); }
            set { SetValue(tbKhachHangProperty, value); }
        }

        // Using a DependencyProperty as the backing store for tbKhachHang.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty tbKhachHangProperty =
            DependencyProperty.Register("tbKhachHang", typeof(DataTable), typeof(frmThuePhong), new UIPropertyMetadata(ViewModels.KhachHangViewModel.GetAllKhachHang()));



        public DataTable tb
        {
            get { return (DataTable)GetValue(tbProperty); }
            set { SetValue(tbProperty, value); }
        }

        // Using a DependencyProperty as the backing store for tb.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty tbProperty =
            DependencyProperty.Register("tb", typeof(DataTable), typeof(frmThuePhong), new UIPropertyMetadata(new DataTable()));



        public frmThuePhong()
        {
            InitializeComponent();
        }


        //************
        public frmThuePhong(ViewModels.PhongViewModel _phong, Command _cm)
        {
            InitializeComponent();
            cm = _cm;
            IsEditMode = _cm == Command.View ? false : true;
        }

        //Khoi tạo phiếu thuê phòng
        private void cbbLoai_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ComboBox).SelectedIndex < 0)
                return;
            if (Phong == null)
                return;
            if ((sender as ComboBox).SelectedIndex == 1)//Theo ngày
                txtGiaVND.Value = Phong.GiaTheoNgay;
            else
                txtGiaVND.Value = Phong.GiaTheoGio;
            txtGiaUSD.Text = ViewModels.PhongViewModel.TinhGiaNgoaiTe(double.Parse(txtGiaVND.Value.ToString()), "USD").ToString();
        }

        //Thêm dòng mới
        private void AddNewRow(int stt)
        {
            if (tb.Rows.Count >= Phong.SucChua)
                return;
            tb.Rows.Add(stt, null, null, null,false);
            xdgThongTinKH.ActiveCell = (xdgThongTinKH.Records[xdgThongTinKH.Records.Count - 1] as DataRecord).Cells["tenkh"];
        }

        //Xóa dòng
        private void DeleteRow(int stt)
        {
            tb.Rows.RemoveAt(stt);
        }

        private void FormTrans_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                txtNgayThue.Text = DateTime.Now.ToString("dd/MM/yyyy");
                txtGioThue.Text = DateTime.Now.ToString("hh:mm:ss");
                Phong = (ViewModels.PhongViewModel)DataContext;
                tbKhachHang = ViewModels.KhachHangViewModel.GetAllKhachHang("makh,tenkh,cmnd,diachi");
                if (cm == Command.Edit)
                {
                    tb = ViewModels.ThuePhongViewModel.GetChiTietPhieuThue(Phong.MaPhong, "stt,makh as tenkh,cmnd,diachi");
                    tb.Columns.Add("xoa");
                    //xdgThongTinKH.DataSource = tb.DefaultView;
                }
                else
                {
                    tb = new DataTable();
                    tb.Columns.Add("stt");
                    tb.Columns.Add("tenkh");
                    tb.Columns.Add("cmnd");
                    tb.Columns.Add("diachi");
                    tb.Columns.Add("xoa");
                }
                xdgThongTinKH.DataSource = tb.DefaultView;

                if (IsEditMode)
                    tbMain.Cm_Save += new ucXToolBar.Execute(tbMain_Cm_Save);

                tbMain.Cm_Exit += new ucXToolBar.Execute(tbMain_Cm_Exit);
                cbbLoai.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "QLKS");
            }
        }

        //
        private int KiemTraKh()
        {
            for (int i = 0; i < tb.Rows.Count; i++)
                if (string.IsNullOrEmpty(tb.Rows[i]["tenkh"].ToString()))
                    return i;
            return -1;
        }
        //CheckValid
        private bool KiemTra()
        {
            if (tb.Rows.Count <= 0)
            {
                MessageBox.Show(M_LAN.Equals("V") ? "Chưa nhập khách hàng!" : "Input some customer, please!", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                xdgThongTinKH.Focus();
                return false;
            }
            int r = KiemTraKh();
            if (r >= 0)
            {
                MessageBox.Show(M_LAN.Equals("V")?"Tên khách hàng không hợp lệ!":"customer name is invalid", "QLKS", MessageBoxButton.OK, MessageBoxImage.Error);
                xdgThongTinKH.ActiveDataItem = xdgThongTinKH.Records[r];
                return false;
            }


            return true;
        }

        //Save
        void tbMain_Cm_Save()
        {
            //Thêm vào CSDL dữ liệu
            if (KiemTra())
            {
                List<string> maKH = new List<string>();
                foreach (DataRow row in tb.Rows)
                    maKH.Add(row["tenkh"].ToString());
                if (cm == Command.New || cm == Command.Copy)
                    maPhieuThuePhong = -1;
                if (cm == Command.Edit)
                    maPhieuThuePhong = ViewModels.ThuePhongViewModel.GetMaPhieuThue(txtMaPhong.Text);
                //-1: thêm phiếu mới
                if (ViewModels.ThuePhongViewModel.ThemPhieuThuePhong(maPhieuThuePhong, txtMaPhong.Text, DateTime.Now.Date, DateTime.Now.TimeOfDay, cbbLoai.SelectedIndex, maKH))
                {
                    Phong.TinhTrang = 2;
                    Phong.TenTinhTrang = Models.PhongModel.GetTenTinhTrang(2);

                    this.UpdateSucces = true;
                    MessageBox.Show(M_LAN.Equals("V")?"Thuê phòng thành công!":"rent room succesful", "HotelManager", MessageBoxButton.OK, MessageBoxImage.Information);
                    Close();
                }
            }
        }

        //Thoát
        void tbMain_Cm_Exit()
        {
            this.Close();
        }

        private void xdgThongTinKH_EditModeEnded(object sender, Infragistics.Windows.DataPresenter.Events.EditModeEndedEventArgs e)
        {
            Cell c = xdgThongTinKH.ActiveCell;
            if (c.Field.Name.Equals("cmnd"))
            {
                if (!c.Value.ToString().Trim().Equals(""))
                    tb.Rows[xdgThongTinKH.ActiveRecord.Index]["stt"] = xdgThongTinKH.ActiveRecord.Index + 1;
                else
                    tb.Rows[xdgThongTinKH.ActiveRecord.Index]["stt"] = "";
            }
        }

        private void txtTextboxComplete_AddNewItem(object sender, EventArgs e)
        {
            frmThemKhachHang frm = new frmThemKhachHang(null,Command.New);
            frm.ShowDialog();
            if (frm.UpdateSucces)
                tbKhachHang = ViewModels.KhachHangViewModel.GetAllKhachHang();
        }

        private void xdgThongTinKH_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F4)
            {
                if (tb.Rows.Count >= Phong.SucChua)
                    return;
                AddNewRow(tb.Rows.Count + 1);
            }
            else if (e.Key != Key.Up && e.Key != Key.Down && e.Key != Key.Enter && e.Key != Key.Tab)
            {
                if (xdgThongTinKH.ActiveCell.Field.Name == "tenkh")
                {
                    object contentHost = SysLib.SysObj.FindChild<TextBoxComplete>((e.OriginalSource as CellValuePresenter), "UcTextBoxComplete");
                    if (contentHost != null)
                        (contentHost as TextBoxComplete).GetFocus();
                }
                else
                {
                    object contentHost = SysLib.SysObj.FindChild<TextBox>((e.OriginalSource as CellValuePresenter), "textbox");
                    if (contentHost != null)
                        (contentHost as TextBox).Focus();
                }
            }
            else if (e.Key == Key.Tab)
            {
                if (xdgThongTinKH.ActiveCell.Field.Name == "diachi")
                {
                    if (tb.Rows.Count == Phong.SucChua)
                    {
                        return;
                    }
                    if (xdgThongTinKH.ActiveRecord.Index == xdgThongTinKH.Records.Count - 1)
                    {
                        e.Handled = true;
                        AddNewRow(xdgThongTinKH.Records.Count + 1);
                    }
                }
            }
        }

        private void xdgThongTinKH_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (e.NewFocus is XamDataGrid)
            {
                if (tb.Rows.Count == 0)
                {
                    AddNewRow(1);
                }
                else
                    xdgThongTinKH.ActiveCell = (xdgThongTinKH.Records[0] as DataRecord).Cells["tenkh"];
            }

        }

        private void textbox_GotFocus(object sender, RoutedEventArgs e)
        {
            (sender as TextBox).SelectAll();
        }

        private void txtTextboxComplete_AddNewItem(object sender, RoutedEventArgs e)
        {
            frmThemKhachHang frm = new frmThemKhachHang();
            frm.ShowDialog();
            if (frm.UpdateSucces)
                tbKhachHang = ViewModels.KhachHangViewModel.GetAllKhachHang();
        }

        private void txtTextboxComplete_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            DataRow[] row = tbKhachHang.Select("makh like'" + xdgThongTinKH.ActiveCell.Value.ToString() + "'");
            if (row.Length > 0)
            {
                tb.Rows[xdgThongTinKH.ActiveRecord.Index]["cmnd"] = row[0]["cmnd"];
                tb.Rows[xdgThongTinKH.ActiveRecord.Index]["diachi"] = row[0]["diachi"];
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int n = tb.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                if (tb.Rows[i]["xoa"].ToString().ToUpper() == "TRUE")
                {
                    tb.Rows.RemoveAt(i);
                    i--;
                    n--;
                }
            }
        }
    }
}
